<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 提起Spring，必然就会联想到AOP（面向切面编程）和IOC（控制反转）这两个词，众所周知，Spring框架对这两种思想进行了很好的实现。 在这篇文章，我将大致的介绍Spring对AOP这思想的实现流程。 对于AOP，关注的两个问题：  什么是是AOP&#x2F;IOC？ AOP&#x2F;IOC解决了什么问题？  一、什么是AOP  Aspect oriented programming">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringAOP知识小结">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/08/19/spring/SpringAOP%E7%9F%A5%E8%AF%86%E5%B0%8F%E7%BB%93/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 提起Spring，必然就会联想到AOP（面向切面编程）和IOC（控制反转）这两个词，众所周知，Spring框架对这两种思想进行了很好的实现。 在这篇文章，我将大致的介绍Spring对AOP这思想的实现流程。 对于AOP，关注的两个问题：  什么是是AOP&#x2F;IOC？ AOP&#x2F;IOC解决了什么问题？  一、什么是AOP  Aspect oriented programming">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/横向切割.png">
<meta property="og:image" content="http://img.xiajibagao.top/小明买房（静态代理）.png">
<meta property="og:image" content="http://img.xiajibagao.top/Spring五种增强类型.png">
<meta property="og:image" content="http://img.xiajibagao.top/Spring提供的六种切点类型.png">
<meta property="og:image" content="http://img.xiajibagao.top/切面类继承关系.png">
<meta property="article:published_time" content="2020-08-18T16:00:00.000Z">
<meta property="article:modified_time" content="2020-11-20T07:31:44.145Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="Spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/横向切割.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/08/19/spring/SpringAOP知识小结/"/>





  <title>SpringAOP知识小结 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/08/19/spring/SpringAOP%E7%9F%A5%E8%AF%86%E5%B0%8F%E7%BB%93/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SpringAOP知识小结</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-08-19T00:00:00+08:00">
                2020-08-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring/" itemprop="url" rel="index">
                    <span itemprop="name">Spring</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>提起Spring，必然就会联想到AOP（面向切面编程）和IOC（控制反转）这两个词，众所周知，Spring框架对这两种思想进行了很好的实现。</p>
<p>在这篇文章，我将大致的介绍Spring对AOP这思想的实现流程。</p>
<p>对于AOP，关注的两个问题：</p>
<ul>
<li>什么是是AOP/IOC？</li>
<li>AOP/IOC解决了什么问题？</li>
</ul>
<h2 id="一-什么是aop">一、什么是AOP</h2>
<blockquote>
<p>Aspect oriented programming 面向切面编程，AOP 是 OOP（面向对象编程）的一种延续。</p>
</blockquote>
<p>我们知道，根据面向对象编程的思想，对于一些具有相同属性和方法的类，我们可以抽象出他们共同部分作为一个父类，然后这些子类通过继承来获得他们共同的属性。比如<code>Cat</code>类和<code>Dog</code>都有<code>eat()</code>方法，那么我们可以将<code>eat()</code>方法抽象到他们的父类<code>Animal</code>，让他们去继承父类。</p>
<p>我们管这个抽取成类的方法叫做<strong>纵向抽取</strong>。</p>
<p>而如果他们的父类的方法中有相同方法，那么就直接抽取成公共方法。，但是有一些一开始就耦合到业务逻辑里的重复代码，比如下面统计方法执行时间的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">eat</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//计时</span></span><br><span class="line">    <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">    System.out.println(<span class="string">&quot;eat.....&quot;</span>);</span><br><span class="line">    <span class="comment">//结束计时</span></span><br><span class="line">    System.out.println(<span class="string">&quot;执行时长：&quot;</span> + (System.currentTimeMillis() - start)/<span class="number">1000f</span> + <span class="string">&quot;s&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看到，这些方法实际上是难以抽离的，因为他们实际上已经耦合到了业务逻辑里。这部分代码，又叫做<strong>横切逻辑代码</strong>。</p>
<figure>
<img src="http://img.xiajibagao.top/横向切割.png" alt="横向切割"><figcaption aria-hidden="true">横向切割</figcaption>
</figure>
<p>我们可以看到，通过对方法增加一个进行一个<strong>横向抽取</strong>来抽取重复的方法。这个方式<strong>不会改变原有的业务逻辑代码</strong>。</p>
<p>现在就不难理解AOP为啥叫面向切面编程了：</p>
<ul>
<li>切指横切逻辑：原有业务代码不动，只操作横切逻辑代码；</li>
<li>以方法为线，横切逻辑代码为点，很多点构成了一个横切面。</li>
</ul>
<h2 id="二-aop的实现原理">二、AOP的实现原理</h2>
<h3 id="1静态代理">1.静态代理</h3>
<p>说到AOP，就得先理解一下什么叫代理模式：</p>
<blockquote>
<p>代理模式给某一个对象提供一个代理对象，并由代理对象控制对原对象的引用。通俗的来讲代理模式就是我们生活中常见的中介。</p>
</blockquote>
<p>我们举个例子，首先有一个接口，叫做购房者，然后这个类地下有一个实现类，叫做小明:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//购房者接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Buyers</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 买房</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">buy</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//小明实现了购房者接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XiaoMing</span> <span class="keyword">implements</span> <span class="title">Buyers</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">buy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;小明买了一套房&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>买房子还要货比三家，小明没时间，于是就把买房子这件事情委托给中介</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Intermediary</span> <span class="keyword">implements</span> <span class="title">Buyers</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> XiaoMing xiaoMing ;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 小明把权限委托给了中介</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Intermediary</span><span class="params">(XiaoMing xiaoMing)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.xiaoMing = xiaoMing;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">buy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 在这基础上又添加了挑选方法</span></span><br><span class="line">        System.out.println(<span class="string">&quot;房中介先帮吗挑了最合适的房&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 中介让XiaoMing这个类执行了购房的动作</span></span><br><span class="line">        xiaoMing.buy();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 在这基础上又添加了抽成方法</span></span><br><span class="line">        System.out.println(<span class="string">&quot;买完房中介要那点抽成&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure>
<img src="http://img.xiajibagao.top/小明买房（静态代理）.png" alt="小明买房（静态代理）"><figcaption aria-hidden="true">小明买房（静态代理）</figcaption>
</figure>
<p>在这个例子里：</p>
<ul>
<li>被代理对象是小明这个类，是我们最终要访问的；</li>
<li>代理对象就是中介这个类，他是被代理对象的加强，我们通过代理对象去访问目标对象，在这基础上对其进行加强。</li>
</ul>
<p>为了做到代理的效果，代理对象和目标对象<strong>需要实现同一个接口或者继承同一个类</strong>，以达到通过代理对象的方法去调用被代理对象的方法。这种方法叫做<strong>静态代理</strong>。</p>
<p>通过静态代理，我们可以在不改变代理类代码的基础上进行方法增强，但是如果有很多这样的代理行为，那么就需要很多代理类或者代理类去实现很多接口的方法，这样做显然会来带麻烦，为此，我们可以选择只在需要的时候才生产代理对象，这就是动态代理。</p>
<p>针对动态代理，有两种实现方法：</p>
<ul>
<li>JDK 代理，通过 JDK 的 API 实现；</li>
<li>CGLib 代理，通过 CGLib 包实现。</li>
</ul>
<h3 id="2jdk代理">2.JDK代理</h3>
<p>JDK 代理仍然需要被代理去实现某个接口，因为 JDK 代理的方式本质仍然还是生成一个与被代理类继承同一个接口的类，去代替被代理类的方法提供调用，但是和静态代理不同，这个代理对象由代码在调用的时候动态生成。</p>
<p>我们可以先看看实现代理效果的核心方法<code>Proxy.newProxyInstance()</code>的注释：</p>
<blockquote>
<p>返回指定接口的代理类的实例，该实例将方法调用分派到指定的调用处理程序。</p>
<p>参数：</p>
<p><code>ClassLoader loader</code>：指定加载被代理对象的类加载器</p>
<p><code>Class&lt;?&gt;[] interfaces</code>：被代理对象实现的接口的类型,使用泛型方式确认类型</p>
<p><code>InvocationHandler h</code>：事件处理,执行被代理对象的方法时,会触发事件处理器的方法,会把当前执行目标对象的方法作为参数传入</p>
</blockquote>
<p>我们需要提供三个参数，被代理类的类的加载器，被代理类实现的结构，一个代理方法要实现的函数式接口。</p>
<p>对于函数式接口 <code>InvocationHandler</code>，我们不妨再看看他的参数：</p>
<blockquote>
<p><code>proxy</code>：在方法上调用方法的代理实例method-与在代理实例上调用的接口方法相对应的Method实例。</p>
<p><code>Method</code>：对象的声明类将是在其中声明该方法的接口，它可能是代理类通过其继承该方法的代理接口的超接口。</p>
<p><code>args</code> ：包含在代理实例的方法调用中传递的参数值的对象数组；如果接口方法不带参数，则为null。基本类型的参数包装在适当的基本包装器类的实例中，例如java.lang.Integer或java.lang.Boolean。</p>
</blockquote>
<p>可以说非常直观了，下面我们来简单实现一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">( String[] args )</span> </span>&#123;</span><br><span class="line">    XiaoMing xiaoMing = <span class="keyword">new</span> XiaoMing();</span><br><span class="line">    <span class="comment">//获取代理对象</span></span><br><span class="line">    Buyers proxyBuyers = (Buyers) Proxy.newProxyInstance(</span><br><span class="line">        <span class="comment">//获取被代理对象的类加载器</span></span><br><span class="line">        xiaoMing.getClass().getClassLoader(),</span><br><span class="line">        <span class="comment">//获取被代理对象实现的接口</span></span><br><span class="line">        xiaoMing.getClass().getInterfaces(),</span><br><span class="line">        <span class="comment">//让代理对象实现被代理对象实现的接口</span></span><br><span class="line">        (proxy, method, params) -&gt; &#123;</span><br><span class="line">            <span class="comment">//只有对buy方法进行加强，如果不是buy方法就直接执行被代理对象的方法</span></span><br><span class="line">            <span class="keyword">if</span> (method.getName() != <span class="string">&quot;buy&quot;</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> method.invoke(xiaoMing, params);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;中介帮小明找到了最合适的房源&quot;</span>);</span><br><span class="line">            method.invoke(xiaoMing, params);</span><br><span class="line">            System.out.println(<span class="string">&quot;中介抽了一笔中介费&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    );</span><br><span class="line">    <span class="comment">//通过代理对象买房</span></span><br><span class="line">    proxyBuyers.buy();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//输出结果</span></span><br><span class="line">中介帮小明找到了最合适的房源</span><br><span class="line">小明买了一套房</span><br><span class="line">中介抽了一笔中介费</span><br></pre></td></tr></table></figure>
<p>我们可以看看实现代理效果的核心方法<code>Proxy.newProxyInstance()</code>的注释：</p>
<blockquote>
<p>返回指定接口的代理类的实例，该实例将方法调用分派到指定的调用处理程序。</p>
<p>参数：</p>
<p><code>ClassLoader loader</code>：指定加载被代理对象的类加载器</p>
<p><code>Class&lt;?&gt;[] interfaces</code>：被代理对象实现的接口的类型,使用泛型方式确认类型</p>
<p><code>InvocationHandler h</code>：事件处理,执行被代理对象的方法时,会触发事件处理器的方法,会把当前执行目标对象的方法作为参数传入</p>
</blockquote>
<h3 id="3cglib代理">3.CGLib代理</h3>
<p>对于动态代理，我们可以通过JDK的<code>Proxy.newProxyInstance()</code>方法动态的生成一个实现了被代理类指定接口的代理类，那么，如果<strong>被代理类没有实现任何接口</strong>，那我们该怎么办呢？答案就是使用 CGLib 代理。</p>
<p>CGLib 代理的原理就是在内存里创建一个被代理类的对象的子类，然后重写父类要加强的方法，而无需加强的方法就直接使用父类方法。</p>
<p>要使用 CGLib 代理，需要引入 CGLib 包（Spring的动态代理就是基于Cglib实现的，所以Spring的依赖里会有这个）</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/cglib/cglib --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>cglib<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cglib<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.3.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>然后我们实现一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">XiaoMing xiaoMing = <span class="keyword">new</span> XiaoMing();</span><br><span class="line"><span class="comment">//获取代理对象</span></span><br><span class="line">Buyers proxyBuyers = (Buyers) Enhancer.create(</span><br><span class="line">    <span class="comment">//获取被代理对象的类</span></span><br><span class="line">    xiaoMing.getClass(),</span><br><span class="line">    <span class="comment">//实现代理逻辑切入类</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">new</span> MethodInterceptor() &#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         *</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> o 代理类对象</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> method 要拦截的被代理类的方法</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> objects 被代理类的方法参数</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> methodProxy 要触发父类的方法对象</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@return</span> </span></span><br><span class="line"><span class="comment">         * <span class="doctag">@throws</span> Throwable</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object o, Method method, Object[] objects, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (method.getName() != <span class="string">&quot;buy&quot;</span>) &#123;</span><br><span class="line">                <span class="comment">//注意，这里参数是o，调用的是invokeSuper</span></span><br><span class="line">                <span class="keyword">return</span> methodProxy.invokeSuper(o, objects);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;中介帮小明找到了最合适的房源&quot;</span>);</span><br><span class="line">            <span class="comment">//注意，这里参数是xiaoMing，调用的是invoke</span></span><br><span class="line">            methodProxy.invoke(xiaoMing, objects);</span><br><span class="line">            System.out.println(<span class="string">&quot;中介抽了一笔中介费&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">);</span><br><span class="line">proxyBuyers.buy();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一般为了方便使用，我们会将代理过程整合到一个代理工厂类中。</p>
<p><strong>由于需要生成子类，所以要被代理的类最好不能用 final 修饰</strong></p>
<h3 id="4如何选择代理模式">4.如何选择代理模式</h3>
<ul>
<li>JDK在创建代理对象时的性能要高于 CGLib 代理，而生成代理对象的运行性能却比 CGLib 的低。</li>
<li>如果是单例的代理，推荐使用 CGLib</li>
</ul>
<p>也就是说，<strong>如果需要频繁的创建代理对象（多例），那么就该选择JDK代理，否则（单例）使用CGLib代理</strong></p>
<h3 id="5其他aop实现">5.其他AOP实现</h3>
<p>除了代理模式以外，还有其他的实现：AspectJ，以及 JBoss API 等，其中 AspectJ 应该是知名度最高的，它常常以注解的形式出现在我们的代码中。</p>
<blockquote>
<p>AspectJ是<strong>语言级别</strong>的 AOP 实现，扩展了 Java 语言，定义了 AOP 语法，能够在<strong>编译期</strong>提供横切代码的织入，所以它有<strong>专门的编译器</strong>用来生成遵守Java字节码规范的 Class 文件。</p>
</blockquote>
<h2 id="三-aop">三、AOP</h2>
<h3 id="1aop的术语">1.AOP的术语</h3>
<ul>
<li><p>连接点（Join point）：SpringAOP基于动态代理实现，是方法拦截，也就是每一个成员方法都是连接点</p></li>
<li><p>切点（Poincut）：具体定位的连接点</p></li>
<li><p>增强/通知（Advice）：添加到切点的一段代码，并且定位切点的方位信息。</p>
<p>SpringAOP提供了<strong>前置，后置，返回，异常，环绕</strong>五种。</p></li>
<li><p>织入（weaving）：将增强/通知添加到连接点上的过程</p></li>
<li><p>引入/引介（Introduction）：允许我们向当前类<strong>添加新方法或者属性</strong>，是一种特色增强。</p></li>
<li><p>切面（Aspect）：切面由切点和增强/通知组成，它既包括了横切逻辑的定义、也包括了连接点的定义。</p></li>
</ul>
<blockquote>
<p>通知/增强包含了需要用于多个应用对象的横切行为；连接点是程序执行过程中能够应用通知的所有点；切点定义了通知/增强被应用的具体位置。其中关键的是切点定义了哪些连接点会得到通知/增强。</p>
</blockquote>
<h3 id="2aop的使用方式">2.AOP的使用方式</h3>
<p>有三种：</p>
<ul>
<li>基于代理实现的AOP：需要实现接口手动创建</li>
<li>纯粹POJOO切面：使用XML配置AOP命名空间</li>
<li><span class="citation" data-cites="AspectJ驱动的切面">@AspectJ驱动的切面</span>：使用注解</li>
</ul>
<h3 id="3spring提供的增强方式">3.Spring提供的增强方式</h3>
<p>总共有五种：</p>
<figure>
<img src="http://img.xiajibagao.top/Spring五种增强类型.png" alt="Spring五种增强类型"><figcaption aria-hidden="true">Spring五种增强类型</figcaption>
</figure>
<h3 id="4切点类型">4.切点类型</h3>
<p>总共有六种：</p>
<figure>
<img src="http://img.xiajibagao.top/Spring提供的六种切点类型.png" alt="Spring提供的六种切点类型"><figcaption aria-hidden="true">Spring提供的六种切点类型</figcaption>
</figure>
<h3 id="5切面类型">5.切面类型</h3>
<p>三种：</p>
<ul>
<li>一般切面</li>
<li>切点切面</li>
<li>引介/引入切面</li>
</ul>
<figure>
<img src="http://img.xiajibagao.top/切面类继承关系.png" alt="切面类继承关系"><figcaption aria-hidden="true">切面类继承关系</figcaption>
</figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Spring/" rel="tag"># Spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/13/jvm/JVM%E5%88%9D%E6%8E%A2%EF%BC%88%E4%BA%94%EF%BC%89%EF%BC%9A%E7%B1%BB%E7%9A%84%E5%AE%9E%E4%BE%8B%E5%8C%96/" rel="next" title="JVM初探（五）：类的实例化">
                <i class="fa fa-chevron-left"></i> JVM初探（五）：类的实例化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/09/26/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/" rel="prev" title="设计模式（一）：工厂模式">
                设计模式（一）：工厂模式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-%E4%BB%80%E4%B9%88%E6%98%AFaop"><span class="nav-text">一、什么是AOP</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-aop%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-text">二、AOP的实现原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E9%9D%99%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-text">1.静态代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2jdk%E4%BB%A3%E7%90%86"><span class="nav-text">2.JDK代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3cglib%E4%BB%A3%E7%90%86"><span class="nav-text">3.CGLib代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F"><span class="nav-text">4.如何选择代理模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E5%85%B6%E4%BB%96aop%E5%AE%9E%E7%8E%B0"><span class="nav-text">5.其他AOP实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-aop"><span class="nav-text">三、AOP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1aop%E7%9A%84%E6%9C%AF%E8%AF%AD"><span class="nav-text">1.AOP的术语</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2aop%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="nav-text">2.AOP的使用方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3spring%E6%8F%90%E4%BE%9B%E7%9A%84%E5%A2%9E%E5%BC%BA%E6%96%B9%E5%BC%8F"><span class="nav-text">3.Spring提供的增强方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E5%88%87%E7%82%B9%E7%B1%BB%E5%9E%8B"><span class="nav-text">4.切点类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E5%88%87%E9%9D%A2%E7%B1%BB%E5%9E%8B"><span class="nav-text">5.切面类型</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
